﻿/*
 * 登录解析
 * 处理登录逻辑，验证客户段提交的账号密码，保存登录信息
 */
using System;
using Qs.Comm;
using Qs.Repository;
using Qs.Repository.Domain;
using Qs.Repository.Interface;


namespace Qs.App.SSO
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginParse
    {

        //这个地方使用IRepository<User> 而不使用UserManagerApp是防止循环依赖
        public IRepository<ModelAdminUser, QsDBContext> _app;         
        private IUnitWork<QsDBContext> _unitWork;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userApp"></param>
        /// <param name="unitWork"></param>
        public LoginParse(   IRepository<ModelAdminUser, QsDBContext> userApp,
             IUnitWork<QsDBContext> unitWork)
        {
            _unitWork = unitWork;
            _app = userApp;
        }

        /// <summary>
        /// 管理端登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public VmUser DoAdmin(PassportLoginRequest model)
        {
            var vmUser = new VmUser();
            try
            {
                model.Trim();
                //获取用户信息
                ModelAdminUser  user = _unitWork.FirstOrDefault<ModelAdminUser>(p => p.UserName==model.Account);
                if (user == null)
                {
                    throw new Exception("用户不存在");
                }
                if (!string.IsNullOrEmpty(model.Password))
                {
                    var pwd = xConv.MD5Encoding(model.Password, xConv.ToStrDateTime(user.CreateTime));
                    if (user.PassWord != pwd)
                    {
                        throw new Exception("密码错误");
                    }
                }                
                if (user.Status == (int)xEnum.ComStatus.Disable)
                {
                    throw new Exception("账号状态异常，可能已停用");
                }
                user = UpdateAdminToken(user);
                vmUser = new SSO.VmUser()
                {
                    UserId = user.Id,
                    Token = user.Token,
                    NickName = user.UserName,
                    UserType = (int)xEnum.UserType.StoreAdmin,
                    Status = xConv.ToInt(user.Status),
                    StoreId = user.StoreId,
                    AdminInfo = new SSO.AdminInfo()
                    {
                        UserName = user.UserName,                       
                    }
                };                 
            }
            catch (Exception ex)
            {
                throw new Exception($"错误,Err:{ex.Message},{ex.StackTrace}");
            }
            return vmUser;
        }

        /// <summary>
        /// 微信登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public VmUser DoWxOrPhone(ReqLoginWx.ReqLoginWxDo model)
        {
            var vmUser = new VmUser();
            //获取用户信息
            ModelUser user = _unitWork.FirstOrDefault<ModelUser>(p => (p.WxOpenId == model.WxOpenIdOrPhone || p.Phone == model.WxOpenIdOrPhone)&&p.StoreId== model.StoreId);
            if (user == null)
            {
                throw new Exception("用户不存在");
            }
            user = UpdateToken(user);
            vmUser = new SSO.VmUser()
            {
                UserId = user.Id,
                Token = user.Token,
                NickName = user.NickName,
                UserType = xConv.ToInt(user.UserType),
                Status = xConv.ToInt(user.Status),
                StoreId = user.StoreId,
                WxInfo = new SSO.WxInfo()
                {
                    WxOpenId = user.WxOpenId,
                    IsBindPhone = string.IsNullOrEmpty(user.Phone) ? false : true,
                    SourceUserId = user.SourceUserId,
                    UrlAvatar = user.UrlAvater
                }
            };
            return vmUser;


        }

        /// <summary>
        /// 修改Token
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public ModelUser UpdateToken(ModelUser userInfo)
        {
            // 同一用户多端登录挤下线
            // var token = Guid.NewGuid().ToString().GetHashCode().ToString("x");
            // userInfo.Token = token;
            // userInfo.TokenTime = DateTime.Now;
            // _app.Update(userInfo); 

            // 同一用户多端登录不挤下线
            var token = userInfo.Token;
            if (userInfo.TokenTime < DateTime.Now.AddDays(-Define.TokenDays)||string.IsNullOrEmpty(token))
            {
                token = Guid.NewGuid().ToString().GetHashCode().ToString("x");
                userInfo.Token = token;
                userInfo.TokenTime = DateTime.Now;
                _unitWork.AddOrUpdate(userInfo);
                _unitWork.Save();
            }
            return userInfo;
        }
        /// <summary>
        /// 修改管理端Token
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public ModelAdminUser UpdateAdminToken(ModelAdminUser userInfo)
        {
            // 同一用户多端登录挤下线
            // var token = Guid.NewGuid().ToString().GetHashCode().ToString("x");
            // userInfo.Token = token;
            // userInfo.TokenTime = DateTime.Now;
            // _app.Update(userInfo); 

            // 同一用户多端登录不挤下线
            var token = userInfo.Token;
            if (userInfo.TokenTime < DateTime.Now.AddDays(-Define.TokenDays) || string.IsNullOrEmpty(token))
            {
                token = Guid.NewGuid().ToString().GetHashCode().ToString("x");
                userInfo.Token = token;
                userInfo.TokenTime = DateTime.Now;
                _unitWork.AddOrUpdate(userInfo);
                _unitWork.Save();
            }
            return userInfo;
        }
    }
}